package com.bole.shiro;

import com.alibaba.fastjson.JSONObject;
import com.bole.data.Result;
import com.bole.data.ResultEnum;
import com.bole.dto.permission.AdminDto;
import com.bole.dto.user.UserDto;
import com.bole.feign.AdminFeign;
import com.bole.feign.reception.UserServiceFeign;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    private UserServiceFeign userServiceFeign;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权逻辑");
        // 授权
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> permissionList = new ArrayList<>();
        authorizationInfo.addStringPermissions(permissionList);
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //假设一个用户名和密码
        String password = "adb1043f4bce716a7b600853d67756c5";//123

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取输入手机号
        String telephone = token.getUsername();
        String  noteCode = token.getUsername();
        // 查询
        Result result = userServiceFeign.getUserByTelephone(telephone);
        UserDto user = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), UserDto.class);
        if (user == null) {
            UserDto userDto = new UserDto();
            userDto.setTelephone(telephone);
            userServiceFeign.saveUserInfo(userDto);
        }

        return new SimpleAuthenticationInfo(user, password, ByteSource.Util.bytes("b737d933"),"");
    }
}
